[UVa] 10583 - Ubiquitous Religions

很久沒有解題了,挑一題簡單的來做 XD

使用Union Find即可,我採用Quick Find,如果用Quick Union應該會更快。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;
int main()
{
for ( int n , m , k = 0 ; cin >> n >> m && ( n != 0 && m != 0 ) ; k ++ )
{
int student[50001] , total = n ;
for ( int i = 1 ; i < n + 1 ; i ++ )
student[i] = i ;
for ( int m2 = 0 , s1 ,s2 ; m2 < m && cin >> s1 >> s2 ; m2 ++ )
{
int r = student[s2] ;
if ( student[s1] == student[s2] )
continue ;
else
{
for ( int i = 1 ; i < n + 1 ; i ++ )
{
if ( student[i] == r )
{
student[i] = student[s1] ;
}
}
total -- ;
}
}
cout << "Case " << k + 1 << ": " << total << endl ;
}
return 0;
}